package com.lemmsoft.offthehook;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class OffTheHookSettings extends Activity implements OnClickListener,OnItemSelectedListener,OnCheckedChangeListener	{
	Intent 				mIntent;
	IOffTheHookService 	mService;
	
	/* GUI hooks */
	ToggleButton 		mButton;
	Spinner				mFaceUp;
	Spinner				mFaceDown;
	Spinner				mMoving;
	CheckBox			mNotify;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
	    
        // Bind to the service if running
		mIntent = new Intent(this, OffTheHookService.class);
		startService(mIntent);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
        
        // Attach to the GUI elements
	    mButton 	= (ToggleButton)findViewById(R.id.toggle_service);
	    mFaceUp 	= (Spinner) 	findViewById(R.id.profile_faceup);
	    mFaceDown 	= (Spinner) 	findViewById(R.id.profile_facedown);
	    mMoving 	= (Spinner) 	findViewById(R.id.profile_moving);
	    mNotify		= (CheckBox)	findViewById(R.id.notify_changes);
	    
	    mButton.setOnClickListener(this);
	    mNotify.setOnCheckedChangeListener(this);
	    
	    // Attach adapters to the spinners
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.profiles, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    mFaceUp  .setAdapter(adapter);
	    mFaceDown.setAdapter(adapter);
	    mMoving  .setAdapter(adapter);
	    
	    mFaceUp  .setOnItemSelectedListener(this);
	    mFaceDown.setOnItemSelectedListener(this);
	    mMoving  .setOnItemSelectedListener(this);
	    
	    // Show info about vibrations if they haven't seen it before
	    SharedPreferences mSettings = getSharedPreferences("OffTheHookSettings", 0);
		if(! mSettings.getBoolean("SeenVibRingWarning", false))	{
			new AlertDialog.Builder(this)
				.setMessage(getText(R.string.vibring_explanation))
		       	.setPositiveButton(android.R.string.ok, null)
		        .show();
				
			mSettings.edit().putBoolean("SeenVibRingWarning", true).commit();
		}
	}
    
    @Override
    public void onDestroy()	{
    	super.onDestroy();
    	unbindService(mConnection);
    }
	
	public void onClick(View called)	{
		try	{
			if(called.getId() == R.id.toggle_service)	{
		    	if(mButton.isChecked())	{
		    		Log.i("OTH", "Starting service");
		    		mService.setRunning(true);
		    	}
		    	else	{
		    		Log.i("OTH", "Stopping service");
		    		mService.setRunning(false);
		    	}
			}
		}
		catch(RemoteException e)	{
			Log.e("OTH", "Couldn't bind to service");
			new AlertDialog.Builder(this)
				.setMessage(getText(R.string.error_nosensor))
		       	.setPositiveButton(android.R.string.ok, null)
		        .show();
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		try	{
			if(buttonView.getId() == R.id.notify_changes)	{
				if(mService != null)	{
					mService.setNotifyOnChange(isChecked);
				}
			}
		}
		catch(RemoteException e)	{
			Log.e("OTH", "Couldn't bind to service");
		}
	}
	
	@Override
	public void onNothingSelected(AdapterView<?> arg0) { /* Do nothing */	}
	
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int selection, long arg3) {
		try	{
			switch(arg0.getId())	{		    		
		    	case R.id.profile_facedown:
		    		mService.setProfile(OffTheHookService.FACE_DOWN, selection);
		    		break;
		    		
		    	case R.id.profile_faceup:
		    		mService.setProfile(OffTheHookService.FACE_UP, selection);
		    		break;
		    		
		    	case R.id.profile_moving:
		    		mService.setProfile(OffTheHookService.MOVING, selection);
		    		break;
			}
		}
		catch(RemoteException e)	{
			Log.e("OTH", "Couldn't bind to service");
		}
	}
	
	/* Service connection stuff -----------------------------------------------------------------*/	
	private ServiceConnection mConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            mService = IOffTheHookService.Stub.asInterface(service);
            try {
            	// Get current settings from the service
				mButton  .setChecked  (mService.running());
				mNotify	 .setChecked  (mService.getNotifyOnChange());
				mFaceUp  .setSelection(mService.getProfile(OffTheHookService.FACE_UP));
				mFaceDown.setSelection(mService.getProfile(OffTheHookService.FACE_DOWN));
				mMoving  .setSelection(mService.getProfile(OffTheHookService.MOVING));
			} catch (RemoteException e) {
				e.printStackTrace();
			}
            
        }
        
        public void onServiceDisconnected(ComponentName className)
        {
        	try	{
	            if(! mService.running())	{
	            	stopService(mIntent);
	            }
        	}
        	catch(RemoteException e)	{
        		Log.i("OTH", "Can't see OTH service, stopping on the offchance");
        		stopService(mIntent); // Just in case it is still running and we can't see it
        	}
        	
            mService = null;
        }
    };
}